import { postTaskCategory } from "./../../api/task";
import {
  postLanguageList,
  postOnlineAll,
  postSexAll,
  postAriModelAll,
  postAllDepartment,
  postAllProfession,
  postAllStage,
  postHeaderNav,
  postAtaList,
  postEngineAll,
  postAviationDetailApplyDeclare,
  postRecommendCity,
  postChinaCity,
  postForeignCity,
  postNationalData,
  postChangeLanguage,
} from "./../../api/api";
import { defineStore } from "pinia";
import {
  postSettingData,
  postOnePageQuery,
  postOnePageQueryAll,
} from "../../api/banner";
import { ref, computed } from "vue";
import type { CertificateItem, EducationItem } from "../../types/profile";
import {
  postProfileEducation,
  postProfileCertificate,
} from "./../../api/profile";
import type {
  AirModelItem,
  AtaItem,
  CareerPlanningItem,
  EngineItem,
  LanguageItem,
  OnlineItem,
  SexItem,
} from "../../types/global";
import { useRoute, useRouter } from "vue-router";
import { useCacheStore } from "./cache";
import { useCountryStore, useMemberStore } from "..";

export const useGlobalStore = defineStore("globalStore", () => {
  const route = useRoute();
  const router = useRouter();
  const useAgreeUrl = ref(); // 用户协议 URL
  const { locale } = useI18n();
  // 头部导航栏数据
  const navHeaderList = ref();

  // 个人中心-语言列表数据
  const languageList = ref<LanguageItem[]>();

  const educationList = ref<EducationItem[]>(); // 教育背景列表
  const certificateList = ref<CertificateItem[]>(); // 证书列表
  const onlineList = ref<OnlineItem[]>(); // 在线状态列表
  const sexList = ref<SexItem[]>(); // 性别列表
  const airModelList = ref<AirModelItem[]>(); // 机型列表
  const engineList = ref<EngineItem[]>(); // 发动机列表
  const configData = ref(); // 配置数据

  const onePageConfigData = ref({});

  const partDesc = ref({
    desc1: "",
    desc2: "",
  }); // 部分描述信息
  const ataList = ref<AtaItem[]>(); // ATA 列表
  const departMentList = ref<CareerPlanningItem[]>(); // 部门列表
  const professionList = ref<CareerPlanningItem[]>(); // 职业列表
  const stageList = ref<CareerPlanningItem[]>(); // 阶段列表

  const aviationDetailApplyDeclare = ref(); // 航空详情申请声明

  // 城市接口
  const contryCitys = ref(); // 城市数据
  const countryCitysTitle = ref<any[]>([]); // 城市标题

  // 国籍数据
  const nationalData = ref();

  // 任务分类
  const taskCategoryList = ref();

  const isLoded = ref(false); // 数据加载状态

  const cacheStore = useCacheStore();

  // 获取所有全局数据
  const getGlobalData = async () => {
    navHeaderList.value = undefined;

    const [
      educationRes,
      certificateRes,
      languageRes,
      onlineRes,
      sexRes,
      airModelRes,
      departmentRes,
      professionRes,
      stageRes,
      headerNavRes,
      ataRes,
      engineRes,
      settingRes,
      onePageQueryRes,
      aviationDetailApplyDeclareRes,
      nationRes,
      taskCategoryRes,
      recommendCityRes,
      chinaCityRes,
      foreignCityRes,
    ] = await Promise.all([
      postProfileEducation(),
      postProfileCertificate(),
      postLanguageList(),
      postOnlineAll(),
      postSexAll(),
      postAriModelAll(),
      postAllDepartment(),
      postAllProfession(),
      postAllStage(),
      postHeaderNav(),
      postAtaList(),
      postEngineAll(),
      postSettingData(),
      postOnePageQueryAll(),
      postAviationDetailApplyDeclare(),
      postNationalData(),
      postTaskCategory(),
      postRecommendCity(),
      postChinaCity(),
      postForeignCity(),
    ])

    educationList.value = educationRes.data;
    certificateList.value = certificateRes.data;

    languageList.value = languageRes.data;

    onlineList.value = onlineRes.data;

    sexList.value = sexRes.data;

    airModelList.value = airModelRes.data;

    departMentList.value = departmentRes.data;

    professionList.value = professionRes.data;

    stageList.value = stageRes.data;

    navHeaderList.value = headerNavRes.data;
    // 处理导航栏路由
    navHeaderList.value.forEach((item, index) => {
      if (route.path.includes(item.path)) {
        if (route.path.split("/").length > 1) {
          let query = route.query;
          goto(route.path, query);
        } else {
          goto(route.path, {
            type_id: navHeaderList.value[index].id,
            ...route.query,
          });
        }
      }
    });

    ataList.value = ataRes.data;

    engineList.value = engineRes.data;

    configData.value = settingRes.data;
    onePageQueryRes.data.forEach((item) => {
      if (item.id == 17) {
        useAgreeUrl.value = item.content;
      }
      if (item.id == 15) {
        onePageConfigData.value.website_desc = item.content;
      }
      if (item.id == 13) {
        partDesc.value.desc2 = item.content;
      }
      if (item.id == 12) {
        partDesc.value.desc1 = item.content;
      }
    });
    aviationDetailApplyDeclare.value = aviationDetailApplyDeclareRes.data;

    nationalData.value = nationRes.data;

    useCountryStore().getCountryData()
    let taskCategory = taskCategoryRes.data;
    // 任务分类列表（根据语言动态切换）
    taskCategoryList.value = taskCategory?.map((item) => {
      if (locale.value == "en") {
        return {
          title: item.en_title,
          ...item,
        };
      }
      if (locale.value == "cn") {
        return {
          title: item.cn_title,
          ...item,
        };
      }
    });

    contryCitys.value = [recommendCityRes.data, chinaCityRes.data, foreignCityRes.data];
    countryCitysTitle.value = [recommendCityRes.msg, chinaCityRes.msg, foreignCityRes.msg];

    const memberStore = useMemberStore();
    memberStore.handlePersonalTags();
    isLoded.value = true;
  };

  // 性别选择项
  const sexSelectOptions = computed(() => {
    let arr = sexList.value?.map((item) => {
      return {
        value: item.id,
        label: item.title,
      };
    });
    return arr;
  });

  // 根据性别 ID 获取性别名称
  const getSexById = (id: string) => {
    let sexName = "";
    sexList.value?.map((item) => {
      if (item.id == parseInt(id)) {
        sexName = item.title;
      }
    });
    return sexName;
  };

  // 根据性别名称获取性别 ID
  const getSexIdBySexName = (sex: string) => {
    let sexId = "";
    sexList.value?.map((item) => {
      if (item.title == sex) {
        sexId = item.id + "";
      }
    });
    return sexId;
  };

  // 性别工具函数
  const sexTools = {
    sexSelectOptions,
    getSexById,
  };

  // 根据 ID 和类型获取规划项名称
  const getPlanById = (id: string, key: string) => {
    let title = "";
    if (key == "depart") {
      title = departMentList.value?.find((item) => item.id == parseInt(id))
        ?.title!;
    } else if (key == "profession") {
      title = professionList.value?.find((item) => item.id == parseInt(id))
        ?.title!;
    } else if (key == "stage") {
      title = stageList.value?.find((item) => item.id == parseInt(id))?.title!;
    }
    return title;
  };

  // 根据类型名称获取类型 ID
  const getTypeIdByTypeTitle = (title: string) => {
    let id = "";
    airModelList.value?.map((item) => {
      if (item.title == title) {
        id = item.id + "";
      }
    });
    return id;
  };

  // 根据 ATA 标题获取 ATA ID
  const getAtaIdByAtaTitle = (ataTitle: string) => {
    let id = "";
    ataList.value?.map((item) => {
      if (item.no == ataTitle) {
        id = item.id + "";
      }
    });
    return id;
  };

  return {
    engineList,
    partDesc,
    configData,
    onePageConfigData,
    navHeaderList,
    languageList,
    educationList,
    certificateList,
    onlineList,
    sexList,
    airModelList,
    isLoded,
    sexTools,
    departMentList,
    professionList,
    stageList,
    ataList,
    aviationDetailApplyDeclare,
    contryCitys,
    countryCitysTitle,
    nationalData,
    useAgreeUrl,
    taskCategoryList,
    getPlanById,
    getGlobalData,
    getSexIdBySexName,
    getAtaIdByAtaTitle,
    getTypeIdByTypeTitle,
  };
});
